package com.atguigu.gmall.payment.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeCloseResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.atguigu.gmall.model.enums.PaymentStatus;
import com.atguigu.gmall.model.enums.PaymentType;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.order.client.OrderFeignClient;
import com.atguigu.gmall.payment.config.AlipayConfig;
import com.atguigu.gmall.payment.service.AlipayService;
import com.atguigu.gmall.payment.service.PaymentService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
public class AlipayServiceImpl implements AlipayService {

    @Autowired
    private AlipayClient alipayClient;

    @Autowired
    private OrderFeignClient orderFeignClient;

    @Autowired
    private PaymentService paymentService;

    @Override
    public String createaliPay(Long orderId) {
        OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderId);

        if("PAID".equals(orderInfo.getOrderStatus()) || "CLOSED".equals(orderInfo.getOrderStatus())){

            return "订单已完成了噢！或者失效了，残念(～￣▽￣)～(～￣▽￣)～(～￣▽￣)～";
        }
        paymentService.savePaymentInfo(orderInfo, PaymentType.ALIPAY.name());

        String form = "";

        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_payment_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_payment_url ); //在公共参数中设置回跳和通知地址

        HashMap<String,Object> hashMap = new HashMap<>();
        hashMap.put("out_trade_no",orderInfo.getOutTradeNo());
        hashMap.put("product_code","FAST_INSTANT_TRADE_PAY");
        hashMap.put("total_amount","0.01");
        hashMap.put("subject",orderInfo.getTradeBody());
        hashMap.put("timeout_express","10m");

        alipayRequest.setBizContent(JSON.toJSONString(hashMap));

        try {
            form = alipayClient.pageExecute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        return form;
    }

    @Override
    public boolean refund(Long orderId) {
        OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderId);
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();

        HashMap<String,Object> hashMap = new HashMap<>();
        hashMap.put("out_trade_no",orderInfo.getOutTradeNo());
        hashMap.put("refund_amount",0.01);
        hashMap.put("out_request_no","颜色有点不喜欢呢");

        request.setBizContent(JSON.toJSONString(hashMap));
        AlipayTradeRefundResponse response = null;

        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response.isSuccess()){
            // 更新交易记录 ： 关闭
            PaymentInfo paymentInfo = new PaymentInfo();
            paymentInfo.setPaymentStatus(PaymentStatus.CLOSED.name());
            paymentService.updatePaymentInfo(orderInfo.getOutTradeNo(),PaymentType.ALIPAY.name(),paymentInfo);

            return true;
        }else {
            System.out.println("调用失败");
            return false;
        }
    }

    @SneakyThrows
    @Override
    public Boolean closePay(Long orderId) {
        OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderId);
        AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
        HashMap<String,Object> hashMap = new HashMap<>();

        hashMap.put("out_trade_no",orderInfo.getOutTradeNo());
        hashMap.put("operator_id","YX01");
        request.setBizContent(JSON.toJSONString(hashMap));

        AlipayTradeCloseResponse response = alipayClient.execute(request);
        if(response.isSuccess()){
            System.out.println("调用成功");
            return true;
        }
        System.out.println("调用失败");
        return false;
    }

    @SneakyThrows
    @Override
    public Boolean checkPayment(Long orderId) {
        OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderId);
        AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
        HashMap<String,Object> hashMap = new HashMap<>();

        hashMap.put("out_trade_no",orderInfo.getOutTradeNo());
        request.setBizContent(JSON.toJSONString(hashMap));
        AlipayTradeCloseResponse response = alipayClient.execute(request);
        if(response.isSuccess()){
            return true;
        }
        return false;
    }
}
